package group.sicher.core.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import group.sicher.core.exception.ResponseException;
import group.sicher.core.exception.base.SicherErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * Created by bootvue@gmail.com
 * Date 2019-04-04 12:16
 * 短信发送
 */
@Slf4j
public class SmsUtil {
    /**
     * @param phone        接收方手机号
     * @param param        短信参数内容,json格式 ,验证码类的传{"code":"......"}
     * @param templateCode 短信模板id
     * @param signName     短信签名
     * @param key
     * @param secret
     * @param url          短信接口url
     * @return
     */
    public static boolean send(String phone, String param, String templateCode, String signName, String key, String secret, String url) {
        boolean flag = false;
        DefaultProfile profile = DefaultProfile.getProfile("default", key, secret);

        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        /*公共参数*/
        request.setSysProtocol(ProtocolType.HTTPS);
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(url);
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        /*短信参数*/
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", param);
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            Map<String, String> res = new Gson().fromJson(data, new TypeToken<Map<String, String>>() {
            }.getType());
            if ("ok".equalsIgnoreCase(res.get("Code"))) {
                flag = true;
                log.info("{} 短信发送成功", phone);
            }
        } catch (ClientException e) {
            log.error("短信发送失败: {}", e);
            throw new ResponseException(SicherErrorCode.SMS_ERROR);
        }
        return flag;
    }
}
